package com.citicup.backend.util;

import lombok.Data;

//返回X天前的日期，字符串
//format xx-yy-zz 20xx年yy月zz日

@Data
public class DateUtil {
    private int year;
    private int month;
    private int day;
    private String DateUtilString;

    public DateUtil(String s) {
        assert s.length() == 8;
        this.DateUtilString = s;
        this.year = Integer.parseInt(s.substring(0, 2));
        this.month = Integer.parseInt(s.substring(3, 5));
        this.day = Integer.parseInt(s.substring(6, 8));
    }

    public DateUtil(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
        String tempMonth;
        String tempDay;

        if (month <= 9) {
            tempMonth = "0" + month;
        } else {
            tempMonth = month + "";
        }
        if (day <= 9) {
            tempDay = "0" + day;
        } else {
            tempDay = "" + day;
        }
        DateUtilString = year + "-" + tempMonth + "-" + tempDay;
    }

    @Override
    public String toString() {
        return DateUtilString;
    }

    public static boolean early(DateUtil x,DateUtil y){
        if (x.year<y.year) return true;
        if (x.year>y.year) return false;
        if (x.month<y.month) return true;
        if (x.month>y.month) return false;
        if (x.day<=y.day) return true;
        return false;}

    public String lastmanydays(int x) {
        DateUtil temp = new DateUtil(this.DateUtilString);
        for (int i = 1; i <= x; i++) {
            temp = temp.last();
        }
        return temp.toString();
    }

    public static String lastDay(String nowadays, int x) {
        DateUtil dateUtil = new DateUtil(nowadays);
        return dateUtil.lastmanydays(x);
    }

    public DateUtil last() {
        if (day != 1) {
            return new DateUtil(year, month, day - 1);
        }
        if (month == 2 || month == 4 || month == 6 || month == 8 || month == 9 || month == 11) {
            return new DateUtil(year, month - 1, 31);
        }
        if (month == 5 || month == 7 || month == 10 || month == 12) {
            return new DateUtil(year, month - 1, 30);
        }
        if (month == 1) {
            return new DateUtil(year - 1, 12, 31);
        }
        if (month == 3) {
            if (DateUtil.judge(year) == 0) {
                return new DateUtil(year, 2, 28);
            } else {
                return new DateUtil(year, 2, 29);
            }
        }
        return null;
    }

    public static int judge(int year) {
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                return 1;
            } else {
                return 0;
            }
        }
        if (year % 4 == 0) {
            return 1;
        } else {
            return 0;
        }
    }

}
